/*
Copyright [2020] [https://www.xiaonuo.vip]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：

1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Snowy源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处，作者声明等。
4.分发源码时候，请注明软件出处 https://gitee.com/xiaonuobase/snowy-layui
5.在修改包名，模块名称，项目代码等时，请注明软件出处 https://gitee.com/xiaonuobase/snowy-layui
6.若您的项目无法满足以上几点，可申请商业授权，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.sys.modular.sysuserstuscore.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.core.context.login.LoginContextHolder;
import vip.xiaonuo.core.enums.CommonStatusEnum;
import vip.xiaonuo.core.exception.ServiceException;
import vip.xiaonuo.core.factory.PageFactory;
import vip.xiaonuo.core.file.FileOperator;
import vip.xiaonuo.core.pojo.page.PageResult;
import vip.xiaonuo.sys.modular.emp.param.SysEmpParam;
import vip.xiaonuo.sys.modular.file.util.DownloadUtil;
import vip.xiaonuo.sys.modular.subjectsclassify.entity.SubjectsClassify;
import vip.xiaonuo.sys.modular.subjectsclassify.service.SubjectsClassifyService;
import vip.xiaonuo.sys.modular.sysuserstuscore.entity.SysUserStuScore;
import vip.xiaonuo.sys.modular.sysuserstuscore.enums.SysUserStuScoreExceptionEnum;
import vip.xiaonuo.sys.modular.sysuserstuscore.mapper.SysUserStuScoreMapper;
import vip.xiaonuo.sys.modular.sysuserstuscore.param.SysUserStuScoreParam;
import vip.xiaonuo.sys.modular.sysuserstuscore.service.SysUserStuScoreService;
import vip.xiaonuo.sys.modular.user.enums.SysUserAdminTypeEnum;
import vip.xiaonuo.sys.modular.user.param.SysUserParam;
import vip.xiaonuo.sys.modular.user.result.SysUserResult;
import vip.xiaonuo.sys.modular.user.service.SysUserDataScopeService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

import static vip.xiaonuo.sys.config.FileConfig.DEFAULT_BUCKET;

/**
 * 学习培训成绩表service接口实现类
 *
 * @author zhang
 * @date 2024-06-20 09:32:18
 */
@Service
public class SysUserStuScoreServiceImpl extends ServiceImpl<SysUserStuScoreMapper, SysUserStuScore> implements SysUserStuScoreService {
    @Resource
    private FileOperator fileOperator;
    @Resource
    private SubjectsClassifyService subjectsClassifyService;
    @Resource
    private SysUserDataScopeService sysUserDataScopeService;

    @Override
    public PageResult<SysUserStuScore> page(SysUserStuScoreParam sysUserStuScoreParam) {
        QueryWrapper<SysUserStuScore> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(sysUserStuScoreParam)) {
            if (ObjectUtil.isNotEmpty(sysUserStuScoreParam.getSubject())) {
                queryWrapper.like("subject", sysUserStuScoreParam.getSubject());
            }
            // 根据科目名称 查询
            if (ObjectUtil.isNotEmpty(sysUserStuScoreParam.getName())) {
                queryWrapper.lambda().eq(SysUserStuScore::getName, sysUserStuScoreParam.getName());
            }
            if (ObjectUtil.isNotEmpty(sysUserStuScoreParam.getUserId())) {
                queryWrapper.lambda().eq(SysUserStuScore::getUserId, sysUserStuScoreParam.getUserId());
            }
        }
        return new PageResult<>(this.page(PageFactory.defaultPage(), queryWrapper));
    }

    @Override
    public List<SysUserStuScore> list(SysUserStuScoreParam sysUserStuScoreParam) {
        return this.list();
    }

    @Override
    public void add(SysUserStuScoreParam sysUserStuScoreParam) {
        SysUserStuScore sysUserStuScore = new SysUserStuScore();
        BeanUtil.copyProperties(sysUserStuScoreParam, sysUserStuScore);
        this.save(sysUserStuScore);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<SysUserStuScoreParam> sysUserStuScoreParamList) {
        sysUserStuScoreParamList.forEach(sysUserStuScoreParam -> {
            SysUserStuScore sysUserStuScore = this.querySysUserStuScore(sysUserStuScoreParam);
            this.removeById(sysUserStuScore.getId());
        });
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(SysUserStuScoreParam sysUserStuScoreParam) {
        SysUserStuScore sysUserStuScore = this.querySysUserStuScore(sysUserStuScoreParam);
        BeanUtil.copyProperties(sysUserStuScoreParam, sysUserStuScore);
        this.updateById(sysUserStuScore);
    }

    @Override
    public SysUserStuScore detail(SysUserStuScoreParam sysUserStuScoreParam) {
        return this.querySysUserStuScore(sysUserStuScoreParam);
    }

    /**
     * 获取学习培训成绩表
     *
     * @author zhang
     * @date 2024-06-20 09:32:18
     */
    private SysUserStuScore querySysUserStuScore(SysUserStuScoreParam sysUserStuScoreParam) {
        SysUserStuScore sysUserStuScore = this.getById(sysUserStuScoreParam.getId());
        if (ObjectUtil.isNull(sysUserStuScore)) {
            throw new ServiceException(SysUserStuScoreExceptionEnum.NOT_EXIST);
        }
        return sysUserStuScore;
    }

    @Override
    public void template(HttpServletResponse response) {
        byte[] fileBytes;
        fileBytes = fileOperator.getFileBytes(DEFAULT_BUCKET, "学习成绩.xlsx");
        String fileName = "学习成绩.xlsx";
        DownloadUtil.download(fileName, fileBytes, response);
    }

    @Override
    public Map<String, Object> gradesAnalyse(SysUserParam sysUserParam) {

        QueryWrapper<SysUserResult> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(sysUserParam)) {
            //根据员工所属机构及授权机构查询
            if (ObjectUtil.isNotEmpty(sysUserParam.getSysEmpParam())) {
                SysEmpParam sysEmpParam = sysUserParam.getSysEmpParam();
                if (ObjectUtil.isNotEmpty(sysEmpParam.getOrgId())) {

                    List<Long> orgIdList = sysUserDataScopeService.getUserDataScopeIdList(LoginContextHolder.me().getSysLoginUserId());
                    //查询属于该机构的，或该机构下级所有的人员
                    queryWrapper.and(q -> q.eq("sys_emp.org_id", sysEmpParam.getOrgId())
                            .or().like("sys_org.pids", sysEmpParam.getOrgId())
                            .or().in(!orgIdList.isEmpty(), "sys_emp.org_id", orgIdList));
                }
            }
            //根据状态查询（0正常 1停用），删除的不会展示在列表
            if (ObjectUtil.isNotEmpty(sysUserParam.getSearchStatus())) {
                queryWrapper.eq("sys_user.status", sysUserParam.getSearchStatus());
            }
        }
        //查询非删除状态，排除超级管理员
        queryWrapper.ne("sys_user.status", CommonStatusEnum.DELETED.getCode())
                .ne("sys_user.admin_type", SysUserAdminTypeEnum.SUPER_ADMIN.getCode());

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("selectList", Collections.emptyList());
        resultMap.put("subjectAvgScoreList", Collections.emptyList());
        resultMap.put("subjectNameList", Collections.emptyList());
        resultMap.put("assessScoreList", Collections.emptyList());

        //只取学员信息
        queryWrapper.eq("sys_pos.name", "学员");
        List<Map<String, Object>> result = this.baseMapper.gradesAnalyse(queryWrapper, sysUserParam.getTeam());

        //按学期， 科目， 平均成绩
        //点击科目， 按单位，平均成绩
        //点击单位， 按 优秀/良好/中等/及格/不及格人数
        gradesAnalyseTeam(sysUserParam, result, resultMap);

        return resultMap;
    }

    //按学期统计
    private void gradesAnalyseTeam(SysUserParam sysUserParam, List<Map<String, Object>> result, Map<String, Object> resultMap) {
        //学期分组
        Map<String, Object> teamKeyMap = new LinkedHashMap<>();

        //当前选择学期
        String team;
        if (StringUtils.isNotEmpty(sysUserParam.getTeam())) {
            team = sysUserParam.getTeam();
        } else {
            Map<String, List<Map<String, Object>>> collect = result.stream().filter(f -> f.get("ORG_NAME") != null).collect(Collectors.groupingBy(e -> e.get("TEAM").toString()));
            teamKeyMap.putAll(collect);
            team = teamKeyMap.keySet().stream().findFirst().get();
        }

        Map<String, List<Map<String, Object>>> subjectKeyMap;
        if (StringUtils.isNotEmpty(sysUserParam.getTeam())
                && StringUtils.isNotEmpty(sysUserParam.getSubject())
                && StringUtils.isNotEmpty(sysUserParam.getUnit())) {
            //点击单位， 按 优秀/良好/中等/及格/不及格人数
            List<Double> userScoreList = result.stream()
                    .filter(f -> team.equals(f.get("TEAM").toString()) && f.get("ORG_NAME") != null
                            && sysUserParam.getSubject().equals(f.get("SUBJECT").toString())
                            && sysUserParam.getUnit().equals(f.get("ORG_NAME").toString()))
                    .map(m -> MapUtil.getDouble(m, "SCORE", 0.0))
                    .collect(Collectors.toList());

            //科目分类集合
            SubjectsClassify subjectsClassify = subjectsClassifyService.getOne(Wrappers.lambdaQuery(SubjectsClassify.class)
                    .eq(SubjectsClassify::getSubjectsName, sysUserParam.getSubject()), false);

            //当前科目配置的总分，如果没有配置默认按100总分
            double fullScore = subjectsClassify == null ? 100 : subjectsClassify.getSubjectsScore();
            //成绩区间分数按总分乘以比例计算的
            //1. 优秀：成绩在90至100分之间，包括90分。
            double yx = fullScore * 85 / 100;
            //2. 良好：成绩在80至89分之间。
            double lh = fullScore * 75 / 100;
            //3. 中等：成绩在70至79分之间。
            //double zd = fullScore * 70 / 100;
            //4. 及格：成绩在60至69分之间。
            double jg = fullScore * 60 / 100;
            // 5. 不及格：成绩低于60分。

            //当前科目，当前单位 优秀/良好/中等/及格/不及格人数
            Map<String, Integer> assessScore = new LinkedHashMap<>();
            String key1 = "优秀";
            String key2 = "良好";
            //String key3 = "中等";
            String key4 = "及格";
            String key5 = "不及格";
            assessScore.put(key1, 0);
            assessScore.put(key2, 0);
            //assessScore.put(key3, 0);
            assessScore.put(key4, 0);
            assessScore.put(key5, 0);

            //计算当前科目 优秀/良好/中等/及格/不及格人数
            for (double score : userScoreList) {
                if (score >= yx) {
                    assessScore.put(key1, assessScore.get(key1) + 1);
                } else if (score >= lh && score < yx) {
                    assessScore.put(key2, assessScore.get(key2) + 1);
                } /*else if (score >= zd && score < lh) {
                    assessScore.put(key3, assessScore.get(key3) + 1);
                }*/ else if (score >= jg && score < lh) {
                    assessScore.put(key4, assessScore.get(key4) + 1);
                } else {
                    assessScore.put(key5, assessScore.get(key5) + 1);
                }
            }
            List<Map<Object, Object>> assessScoreList = new ArrayList<>();
            for (String key : assessScore.keySet()) {
                Map<Object, Object> tempMap = MapUtil.builder()
                        .put("name", key)
                        .put("value", assessScore.get(key)).build();
                assessScoreList.add(tempMap);
            }
            resultMap.put("assessScoreList", assessScoreList);
        } else {
            if (StringUtils.isNotEmpty(sysUserParam.getTeam())
                    && StringUtils.isNotEmpty(sysUserParam.getSubject())) {
                //点击科目， 按单位，平均成绩
                subjectKeyMap = result.stream()
                        .filter(f -> team.equals(f.get("TEAM").toString()) && f.get("ORG_NAME") != null
                                && sysUserParam.getSubject().equals(f.get("SUBJECT").toString()))
                        .peek(m -> m.put("SUBJECT", m.get("SUBJECT").toString().replaceAll(" ", "")))
                        .collect(Collectors.groupingBy(e -> e.get("ORG_NAME").toString()));
            } else {
                //选择学期， 按科目， 平均成绩
                subjectKeyMap = result.stream()
                        .filter(f -> team.equals(f.get("TEAM").toString()) && f.get("ORG_NAME") != null)
                        .peek(m -> m.put("SUBJECT", m.get("SUBJECT").toString().replaceAll(" ", "")))
                        .collect(Collectors.groupingBy(e -> e.get("SUBJECT").toString()));
            }

            //各科目 名称
            List<String> subjectNameList = new ArrayList<>();
            //各科目 平均成绩
            List<String> subjectAvgScoreList = new ArrayList<>();

            for (String subject : subjectKeyMap.keySet()) {
                subjectNameList.add(subject);
                List<Map<String, Object>> subjectMaps = subjectKeyMap.get(subject);
                //按科目获取平均成绩
                Double avgScore = subjectMaps.stream().collect(Collectors.averagingDouble(item -> MapUtil.getDouble(item, "SCORE", 0.0)));
                BigDecimal bigDecimal = BigDecimal.valueOf(avgScore).setScale(2, RoundingMode.HALF_UP);
                subjectAvgScoreList.add(bigDecimal.toString());
            }

            resultMap.put("selectList", teamKeyMap.keySet());
            resultMap.put("subjectAvgScoreList", subjectAvgScoreList);
            resultMap.put("subjectNameList", subjectNameList);
        }
    }

    //按学期统计
    private void gradesAnalyseTeam2(SysUserParam sysUserParam, List<Map<String, Object>> result, Map<String, Object> resultMap) {
        //学期分组
        Map<String, Object> teamKeyMap = new LinkedHashMap<>();
        //当前选择学期
        String team;
        if (StringUtils.isNotEmpty(sysUserParam.getTeam())) {
            team = sysUserParam.getTeam();
        } else {
            Map<String, List<Map<String, Object>>> collect = result.stream().filter(f -> f.get("ORG_NAME") != null).collect(Collectors.groupingBy(e -> e.get("TEAM").toString()));
            teamKeyMap.putAll(collect);
            team = teamKeyMap.keySet().stream().findFirst().get();
        }
        //各单位分组
        Map<String, List<Map<String, Object>>> orgNameKeyMap = result.stream().filter(f -> team.equals(f.get("TEAM").toString()) && f.get("ORG_NAME") != null).collect(Collectors.groupingBy(e -> e.get("ORG_NAME").toString()));

        //科目分类集合
        List<SubjectsClassify> subjectsClassifyList = subjectsClassifyService.list();
        //按科目为key存储，方便后面获取
        Map<String, Double> subjectsClassifyMap = new HashMap<>();
        for (SubjectsClassify subjectsClassify : subjectsClassifyList) {
            subjectsClassifyMap.put(subjectsClassify.getSubjectsName(), subjectsClassify.getSubjectsScore());
        }

        //各科目 平均成绩
        List<List<String>> avgScoreList = new ArrayList<>();
        //各单位 各科目 优秀/良好/中等/及格/不及格人数
        Map<String, Map<String, Map<String, Integer>>> assessScoreMap = new LinkedHashMap<>();
        //科目结果集
        List<String> subjectList = new ArrayList<>();
        subjectList.add("科目");
        for (String orgName : orgNameKeyMap.keySet()) {
            //所属单位
            List<String> orgNameList = new ArrayList<>();
            orgNameList.add(orgName);

            Map<String, Map<String, Integer>> subjectAssessScoreMap = new HashMap<>();

            Map<String, List<Map<String, Object>>> subjectKeyMap = orgNameKeyMap.get(orgName).stream().collect(Collectors.groupingBy(e -> e.get("SUBJECT").toString()));
            for (String subject : subjectKeyMap.keySet()) {
                List<Map<String, Object>> subjectMaps = subjectKeyMap.get(subject);
                if (!subjectList.contains(subject)) {
                    subjectList.add(subject);
                }
                //按科目获取平均成绩
                Double avgScore = subjectMaps.stream().collect(Collectors.averagingDouble(item -> MapUtil.getDouble(item, "SCORE", 0.0)));
                BigDecimal bigDecimal = BigDecimal.valueOf(avgScore).setScale(2, RoundingMode.HALF_UP);
                orgNameList.add(bigDecimal.toString());

                //当前科目 优秀/良好/中等/及格/不及格人数
                assessmentMethods(subject, subjectsClassifyMap, subjectMaps, subjectAssessScoreMap);
            }

            avgScoreList.add(orgNameList);
            assessScoreMap.put(orgName, subjectAssessScoreMap);
        }
        if (!avgScoreList.isEmpty()) {
            avgScoreList.add(0, subjectList);
        }

        resultMap.put("selectList", teamKeyMap.keySet());
        resultMap.put("avgDataList", avgScoreList);
        resultMap.put("assessScoreMap", assessScoreMap);
    }

    //按所属单位统计
    private void gradesAnalyseOrgName(SysUserParam sysUserParam, List<Map<String, Object>> result, Map<String, Object> resultMap) {
        //所属单位分组
        Map<String, Object> orgNameKeyMap = new LinkedHashMap<>();
        //当前选择所属单位
        String orgName;
        if (sysUserParam.getSysEmpParam() != null && StringUtils.isNotEmpty(sysUserParam.getSysEmpParam().getOrgName())) {
            orgName = sysUserParam.getSysEmpParam().getOrgName();
        } else {
            Map<String, List<Map<String, Object>>> collect = result.stream()
                    .filter(f -> f.get("ORG_NAME") != null)
                    .collect(Collectors.groupingBy(e -> e.get("ORG_NAME").toString()));
            orgNameKeyMap.putAll(collect);
            orgName = orgNameKeyMap.keySet().stream().findFirst().get();
        }
        //各学期分组
        Map<String, List<Map<String, Object>>> teamKeyMap = result.stream().filter(item -> orgName.equals(ObjectUtil.toString(item.get("ORG_NAME")))).collect(Collectors.groupingBy(e -> e.get("TEAM").toString()));

        //科目分类集合
        List<SubjectsClassify> subjectsClassifyList = subjectsClassifyService.list();
        //按科目为key存储，方便后面获取
        Map<String, Double> subjectsClassifyMap = new HashMap<>();
        for (SubjectsClassify subjectsClassify : subjectsClassifyList) {
            subjectsClassifyMap.put(subjectsClassify.getSubjectsName(), subjectsClassify.getSubjectsScore());
        }

        //各科目 平均成绩
        List<List<String>> avgScoreList = new ArrayList<>();
        //各单位 各科目 优秀/良好/中等/及格/不及格人数
        Map<String, Map<String, Map<String, Integer>>> assessScoreMap = new LinkedHashMap<>();
        //科目结果集
        List<String> subjectList = new ArrayList<>();
        subjectList.add("科目");
        for (String team : teamKeyMap.keySet()) {
            //所属学期
            List<String> teamList = new ArrayList<>();
            teamList.add(team);

            Map<String, Map<String, Integer>> subjectAssessScoreMap = new HashMap<>();

            Map<String, List<Map<String, Object>>> subjectKeyMap = teamKeyMap.get(team).stream().collect(Collectors.groupingBy(e -> e.get("SUBJECT").toString()));
            for (String subject : subjectKeyMap.keySet()) {
                List<Map<String, Object>> subjectMaps = subjectKeyMap.get(subject);
                if (!subjectList.contains(subject)) {
                    subjectList.add(subject);
                }
                //按科目获取平均成绩
                Double avgScore = subjectMaps.stream().collect(Collectors.averagingDouble(item -> MapUtil.getDouble(item, "SCORE", 0.0)));
                BigDecimal bigDecimal = BigDecimal.valueOf(avgScore).setScale(2, RoundingMode.HALF_UP);
                teamList.add(bigDecimal.toString());

                assessmentMethods(subject, subjectsClassifyMap, subjectMaps, subjectAssessScoreMap);
            }

            avgScoreList.add(teamList);
            assessScoreMap.put(team, subjectAssessScoreMap);
        }
        if (!avgScoreList.isEmpty()) {
            avgScoreList.add(0, subjectList);
        }

        resultMap.put("selectList", orgNameKeyMap.keySet());
        resultMap.put("avgDataList", avgScoreList);
        resultMap.put("assessScoreMap", assessScoreMap);
    }

    private static void assessmentMethods(String subject, Map<String, Double> subjectsClassifyMap, List<Map<String, Object>> subjectMaps, Map<String, Map<String, Integer>> subjectAssessScoreMap) {
        //当前科目 优秀/良好/中等/及格/不及格人数
        Map<String, Integer> assessScore = new HashMap<>();
        String key1 = "优秀";
        String key2 = "良好";
        String key3 = "中等";
        String key4 = "及格";
        String key5 = "不及格";
        assessScore.put(key1, 0);
        assessScore.put(key2, 0);
        assessScore.put(key3, 0);
        assessScore.put(key4, 0);
        assessScore.put(key5, 0);

        //当前科目配置的总分，如果没有配置默认按100总分
        double fullScore = subjectsClassifyMap.get(subject) == null ? 100 : subjectsClassifyMap.get(subject);
        //成绩区间分数按总分乘以比例计算的
        //1. 优秀：成绩在90至100分之间，包括90分。
        double yx = fullScore * 90 / 100;
        //2. 良好：成绩在80至89分之间。
        double lh = fullScore * 80 / 100;
        //3. 中等：成绩在70至79分之间。
        double zd = fullScore * 70 / 100;
        //4. 及格：成绩在60至69分之间。
        double jg = fullScore * 60 / 100;
        // 5. 不及格：成绩低于60分。

        //计算当前科目 优秀/良好/中等/及格/不及格人数
        for (Map<String, Object> subjectMap : subjectMaps) {
            double score = MapUtil.getDouble(subjectMap, "SCORE", 0.0);
            if (score >= yx) {
                assessScore.put(key1, assessScore.get(key1) + 1);
            } else if (score >= lh && score < yx) {
                assessScore.put(key2, assessScore.get(key2) + 1);
            } else if (score >= zd && score < lh) {
                assessScore.put(key3, assessScore.get(key3) + 1);
            } else if (score >= jg && score < zd) {
                assessScore.put(key4, assessScore.get(key4) + 1);
            } else {
                assessScore.put(key5, assessScore.get(key5) + 1);
            }
        }
        subjectAssessScoreMap.put(subject, assessScore);
    }

    @Override
    public Map<String, Object> gradesAnalyseData(SysUserParam sysUserParam) {

        QueryWrapper<SysUserResult> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotNull(sysUserParam)) {
            //根据员工所属机构及授权机构查询
            if (ObjectUtil.isNotEmpty(sysUserParam.getSysEmpParam())) {
                SysEmpParam sysEmpParam = sysUserParam.getSysEmpParam();
                if (ObjectUtil.isNotEmpty(sysEmpParam.getOrgId())) {

                    List<Long> orgIdList = sysUserDataScopeService.getUserDataScopeIdList(LoginContextHolder.me().getSysLoginUserId());
                    //查询属于该机构的，或该机构下级所有的人员
                    queryWrapper.and(q -> q.eq("sys_emp.org_id", sysEmpParam.getOrgId())
                            .or().like("sys_org.pids", sysEmpParam.getOrgId())
                            .or().in(!orgIdList.isEmpty(), "sys_emp.org_id", orgIdList));
                }
            }
            //根据状态查询（0正常 1停用），删除的不会展示在列表
            if (ObjectUtil.isNotEmpty(sysUserParam.getSearchStatus())) {
                queryWrapper.eq("sys_user.status", sysUserParam.getSearchStatus());
            }
        }
        //查询非删除状态，排除超级管理员
        queryWrapper.ne("sys_user.status", CommonStatusEnum.DELETED.getCode())
                .ne("sys_user.admin_type", SysUserAdminTypeEnum.SUPER_ADMIN.getCode());

        //只取学员信息
        queryWrapper.eq("sys_pos.name", "学员");
        List<Map<String, Object>> result = this.baseMapper.gradesAnalyseData(queryWrapper, sysUserParam.getTeam());

        Map<String, List<Map<String, Object>>> orgNameKeyMap = result.stream().filter(f -> f.get("ORG_NAME") != null).collect(Collectors.groupingBy(e -> e.get("ORG_NAME").toString()));

        Map<String, Double> indicatorMap = new LinkedHashMap<>();
        indicatorMap.put("成绩", 0.0);
        indicatorMap.put("立功受奖", 0.0);
        indicatorMap.put("大项活动", 0.0);
        indicatorMap.put("学习经历", 0.0);
        indicatorMap.put("工作经历", 0.0);
        List<Map<String, Object>> radarData = new ArrayList<>();
        for (String key : orgNameKeyMap.keySet()) {
            List<Map<String, Object>> values = orgNameKeyMap.get(key);
            double scoreSum = values.stream().filter(f -> f.get("SCORE_SUM") != null).map(m -> m.get("SCORE_SUM").toString()).collect(Collectors.averagingDouble(Double::parseDouble));
            double merSize = values.stream().filter(f -> f.get("MER_SIZE") != null).map(m -> m.get("MER_SIZE").toString()).mapToDouble(Double::parseDouble).sum();
            double activitySize = values.stream().filter(f -> f.get("ACTIVITY_SIZE") != null).map(m -> m.get("ACTIVITY_SIZE").toString()).mapToDouble(Double::parseDouble).sum();
            double leveltrainSize = values.stream().filter(f -> f.get("LEVELTRAIN_SIZE") != null).map(m -> m.get("LEVELTRAIN_SIZE").toString()).mapToDouble(Double::parseDouble).sum();
            double dutiesSize = values.stream().filter(f -> f.get("DUTIES_SIZE") != null).map(m -> m.get("DUTIES_SIZE").toString()).mapToDouble(Double::parseDouble).sum();

            Map<String, Object> tempMap = new HashMap<>();
            tempMap.put("sort", values.get(0).getOrDefault("SORT", "0"));
            tempMap.put("name", key);
            tempMap.put("value", new Double[]{scoreSum, merSize, activitySize, leveltrainSize, dutiesSize});
            radarData.add(tempMap);

            if (indicatorMap.containsKey("工作经历")) {
                Double v = indicatorMap.get("工作经历");
                if (dutiesSize > v) {
                    indicatorMap.put("工作经历", dutiesSize);
                }
            } else {
                indicatorMap.put("工作经历", dutiesSize);
            }

            if (indicatorMap.containsKey("学习经历")) {
                Double v = indicatorMap.get("学习经历");
                if (leveltrainSize > v) {
                    indicatorMap.put("学习经历", leveltrainSize);
                }
            } else {
                indicatorMap.put("学习经历", leveltrainSize);
            }

            if (indicatorMap.containsKey("大项活动")) {
                Double v = indicatorMap.get("大项活动");
                if (activitySize > v) {
                    indicatorMap.put("大项活动", activitySize);
                }
            } else {
                indicatorMap.put("大项活动", activitySize);
            }

            if (indicatorMap.containsKey("立功受奖")) {
                Double v = indicatorMap.get("立功受奖");
                if (merSize > v) {
                    indicatorMap.put("立功受奖", merSize);
                }
            } else {
                indicatorMap.put("立功受奖", merSize);
            }

            if (indicatorMap.containsKey("成绩")) {
                Double v = indicatorMap.get("成绩");
                if (scoreSum > v) {
                    indicatorMap.put("成绩", scoreSum);
                }
            } else {
                indicatorMap.put("成绩", scoreSum);
            }

        }

        List<Map<String, Object>> radarIndicator = new ArrayList<>();
        for (String key : indicatorMap.keySet()) {
            Map<String, Object> tempMap = new HashMap<>();
            Double v = indicatorMap.get(key);
            tempMap.put("name", key);
            tempMap.put("max", v);
            radarIndicator.add(tempMap);
        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("listData", result);
        resultMap.put("radarData", radarData.stream().sorted(Comparator.comparing(obj -> Integer.parseInt(((Map<?, ?>) obj).get("sort").toString()))));
        resultMap.put("radarIndicator", radarIndicator);

        return resultMap;
    }

}
